//
//  NetworkTools.swift
//  SHWeibo2.0
//
//  Created by 黄礼潮 on 16/2/24.
//  Copyright © 2016年 黄礼潮. All rights reserved.
//

import UIKit
import AFNetworking

enum CZRequestMethod:String{

    case GET = "GET"
    case POST = "POST"

}

class NetworkTools: AFHTTPSessionManager {
    
    /// MARK --- 应用程序信息
     let appKey = "1502115466"
     let appSecret = "aaf4e19bef12ad18c79274ad6b0e96a8"
     let redirectUri = "http://www.baidu.com"
    
    static let shardTools:NetworkTools = {
    
       let tools = NetworkTools(baseURL: nil)
       //设置JSON反序列化支持的文本的格式
       tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        //请求设置的时间，默认是60s
       tools.requestSerializer.timeoutInterval = 15
        //过滤控制，防止第三方框架会崩溃
       (tools.responseSerializer as! AFJSONResponseSerializer).removesKeysWithNullValues  = true
      
        //启动连接状态监听  ---通过通知中心发布
        tools.reachabilityManager.startMonitoring()
        
        
     
       return tools
    }()
    
    deinit{
     
        //停止连接状态
        reachabilityManager.stopMonitoring()
    
    }
    
    //定义一个属性
    var reachability: Bool{
    
      return reachabilityManager.reachable
    }

}
//MARK --- OAuth相关方法
extension NetworkTools{
 
    var oAuthNSURL: NSURL{
    
    let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUri)"
    
    return NSURL(string: urlString)!
    }

}


extension NetworkTools {
   
    func request(method:CZRequestMethod,URLString:String,parameters:[String:AnyObject]?,finished:(result:[String:AnyObject]?)->()){
    
        let success = {(task:NSURLSessionDataTask, result:AnyObject?) -> Void in
          
            if let result = result as?[String:AnyObject]{
            
                 finished(result: result)
            }else{
             
                print("数据格式错误")
                finished(result: nil)
            }
        }
        
        let failure = { (task:NSURLSessionDataTask?, error:NSError) -> Void in
            
            print("网络请求错误\(error)")
            finished(result: nil)
       }
        
        if method == .GET {
        
            GET(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
        
            POST(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
    
    //上传文件
    func upload(urlString:String,para:[String:AnyObject]?,
        data:NSData,name:String,
        finished:(result:[String:AnyObject]?)->()
        )->(){
        //        let formData: AFMultipartFormData
        /**
        参数
        
        1. data 要上传到服务器的二进制数据
        2. name 服务器指定上传数据的 `字段名`，在开发的时候，一定要咨询后台或者查阅文档，新浪微博 pic
        3. fileName 保存在服务器上的文件名，目前大多数公司的服务器接口，`文件名可以随便值`，后台接口会自动生成文件名
        后台接口，在接收到上传图片后，会生成缩略图／中等尺寸图／大图／原图
        4. mimeType 告诉服务器上传二进制数据的类型，与 contentType 等价
        格式：
        大类型/小类型
        text/plain
        text/html
        image/png
        image/jpg
        image/gif
        如果不知道准确的 mimeType，例如上传图片有 png／jpg／gif，可以直接使用二进制数据的 mimeType
        application/octet-stream
        application/json
        */
            POST(urlString, parameters: para, constructingBodyWithBlock: { (formdata) -> Void in
            
            formdata.appendPartWithFileData(data, name:name, fileName:"hlc", mimeType:"application/octet-stream")
            
            }, progress: nil, success: { (_, responseObject) -> Void in
                
                if let result = responseObject as? [String:AnyObject]{
                    finished(result: result)
                }else{
                    print("数据格式错误")
                    finished(result: nil)
                }
                
            }) { (_, error) -> Void in
                 print("网络请求错误\(error)")
                finished(result:nil)
       }
    }
}
